/**
 * 属性集处理类
 */
export default class Properties {

    #values = {};

    constructor(content) {
        if (content) {
            if (typeof content === 'string') {
                let lines = content.split('\n');
                for (let line of lines) {
                    let index = line.indexOf('=');
                    if (index > 0) {
                        let key = line.substring(0, index).trim();
                        let value = line.substring(index + 1).trim();
                        this.#values[key] = value.trim();
                    }
                }
            } else if (typeof content === 'object') {
                Object.assign(this.#values, content);
            }
        }
    }

    /**
     * 获取值
     * @param key 键
     * @return {String} 值
     */
    get(key) {
        return this.#values[key];
    }

    /**
     * 设置值
     * @param {String} key 键
     * @param {String} value 值
     */
    set(key, value) {
        if (value && typeof value === 'string') {
            value = value.trim();
        }
        this.#values[key] = value;
    }

    /**
     * 仅当值不存在时设置
     * @param {String} key 键
     * @param {String} value 值
     * @returns {boolean} 是否设置成功
     */
    setIfAbsent(key, value) {
        let v = this.get(key);
        if (v === undefined || v === null) {
            this.set(key, value);
            return true;
        }
        return false;
    }

    toString() {
        let lines = [];
        for (let key in this.#values) {
            lines.push(key + '=' + this.#values[key]);
        }
        return lines.join('\n') + '\n';
    }

}
